// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/chapters/[chapterId]/_components/chapter-video-form.tsx
'use client';

import {Chapter, Course, MuxData} from "@prisma/client";
import * as z from "zod";

interface Props {
    initialData: Chapter & { muxData?: MuxData | null }
    courseId: string
    chapterId: string
}

const formSchema = z.object({
    videoUrl: z.string().min(1)
})

import React, {useState} from 'react';
import {useRouter} from "next/navigation";
import toast from "react-hot-toast";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";
import {Button} from "@/components/ui/button";
import {ImageIcon, Pencil, PlusCircle, Video} from "lucide-react";
import Image from "next/image";
import FileUpload from "@/components/learn/file-upload";

const ChapterVideoForm = ({
                              initialData, courseId, chapterId
                          }: Props) => {
    const router = useRouter()

    const [isEditing, setIsEditing] = useState(false)
    const toggleEdit = () => setIsEditing((current) => !current)

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}`, {
                method: "PATCH",
                // body: JSON.stringify({
                //     videoUrl: 'http://localhost:3000' + values.videoUrl,
                // }),
                body: JSON.stringify(values),
                headers: {
                    "Content-Type": "application/json"
                }
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success(`更新成功`)
            toggleEdit()
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    const {mutate: uploadImg, isPending} = useGenerateUploadUrl();

    return (
        <div className={`mt-6 border bg-slate-100 rounded-md p-4`}>
            <div className={`font-medium flex items-center justify-between`}>
                Chapter video
                <Button variant={'ghost'}
                        onClick={toggleEdit}>
                    {isEditing && (
                        <>Cancel</>
                    )}
                    {!isEditing && !initialData.videoUrl && (
                        <>
                            <PlusCircle className={`size-4 mr-2`}/>
                            Add an video
                        </>
                    )}
                    {!isEditing && initialData.videoUrl && (
                        <>
                            <Pencil className={`size-4 mr-2`}/>
                            Edit video
                        </>
                    )}
                </Button>
            </div>
            {!isEditing && (
                !initialData.videoUrl ? (
                    <div className={`flex items-center justify-center h-60 bg-slate-200 rounded-md`}>
                        <Video className={`size-10 text-slate-500`}/>
                    </div>
                ) : (
                    <div className={`relative aspect-video mt-2`}>
                        <video
                            controls
                            src={initialData.videoUrl}
                        />
                    </div>
                )
            )}
            {isEditing && (
                <div>
                    <FileUpload
                        accept={'video/*'}
                        // endpoint={'courseImage'}
                        onChange={async (f) => {
                            if (f) {
                                let url = await uploadImg({
                                    // @ts-ignore
                                    image: f,
                                    prefix: `course/${courseId}`,
                                    // prefix: `_next-video/course/${courseId}`
                                })
                                if (!url || isPending) return
                                await onSubmit({videoUrl: url})
                            }
                        }}
                    />
                    <div className={`text-xs text-muted-foreground mt-4`}>
                        Upload this chapter&apos;s video
                    </div>
                </div>
            )}
            {initialData.videoUrl && !isEditing && (
                <div className={`text-xs text-muted-foreground mt-2`}>
                    Videos can take a few minutes to precess. Refresh the page if video does not appear.
                </div>
            )}
        </div>
    );
};

export default ChapterVideoForm;